package com.pansoft.mobilefitness.view;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.Transformation;
import android.widget.TextView;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.mobilefitness.R;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2019/1/28 18:03
 * @desc :
 * @version: 1.0
 */
public class CircleBar extends View {


    /**
     * 进度条最大值，默认为100
     */
    private int maxValue = 100;

    /**
     * 当前进度值
     */
    private int currentValue = 0;

    /**
     * 每次扫过的角度，用来设置进度条圆弧所对应的圆心角，alphaAngle=(currentValue/maxValue)*360
     */
    private float alphaAngle;

    /**
     * 底部圆弧的颜色，默认为Color.LTGRAY
     */
    private int firstColor;

    /**
     * 进度条圆弧块的颜色
     */
    private int secondColor;

    /**
     * 圆环的宽度
     */
    private int circleWidth;

    /**
     * 画圆弧的画笔
     */
    private Paint circlePaint;

    /**
     * 画文字的画笔
     */
    private Paint textPaint;

    private Paint stepPaint;

    private Paint downSecondPaint;

    private Paint downPaint;

    /**
     * 最上面与最下面文字的颜色
     */
    private int upAndDownColor;

    /**
     * 倒数第二行的文字
     */
    private int downSecondColor;
    /**
     * 渐变圆周颜色数组
     */
    private int[] colorArray = new int[]{Color.parseColor("#f49432")
            , Color.parseColor("#1aae95")};

    /**
     * // 圆圈的矩形范围
     */
    private RectF mColorWheelRectangle = new RectF();

    private Paint textPaint1;
    /**
     * // 中间文字内容
     */
    private int mText;
    /**
     * 中间文字大小
     */

    private int mTextSize;
    /**
     * // 上下文字大小
     */
    private int mTextSize1;
    /**
     * // 上下文字的距离
     */
    private int mDistance;

    public CircleBar(Context context) {
        this(context, null);
    }

    public CircleBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.healthCircleProgressBar,
                defStyle, 0);
        int n = ta.getIndexCount();

        for (int i = 0; i < n; i++) {
            int attr = ta.getIndex(i);
            if (attr == R.styleable.healthCircleProgressBar_firstColor) {
                // 默认底色为亮灰色
                firstColor = ta.getColor(attr, Color.LTGRAY);

            } else if (attr == R.styleable.healthCircleProgressBar_secondColor) {
                // 默认进度条颜色为蓝色
                secondColor = ta.getColor(attr, Color.BLUE);

            } else if (attr == R.styleable.healthCircleProgressBar_circleWidth) {
                circleWidth = ta.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                        // 默认圆弧宽度为6dp
                        TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));

            } else if (attr == R.styleable.healthCircleProgressBar_upAndDownColor) {
                upAndDownColor = ta.getColor(attr, Color.GRAY);
            } else if (attr == R.styleable.healthCircleProgressBar_downSecondColor) {
                downSecondColor = ta.getColor(attr, Color.BLACK);
            }
        }
        ta.recycle();

        init();
    }

    private void init() {
        circlePaint = new Paint();
        circlePaint.setAntiAlias(true); // 抗锯齿
        circlePaint.setDither(true); // 防抖动
        circlePaint.setStrokeWidth(circleWidth);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setDither(true);


        mTextSize = dip2px(getContext(), 40);// 中间文字大小
        // 上面文字大小
        mTextSize1 = dip2px(getContext(), 13);
        mDistance = dip2px(getContext(), 32);//文字间的距离


        // 中间文字的画笔
        textPaint = new Paint(Paint.LINEAR_TEXT_FLAG);
        textPaint.setAntiAlias(true);
        textPaint.setColor(Color.parseColor("#f7931e"));
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextAlign(Paint.Align.LEFT);
        textPaint.setTextSize(mTextSize);
        //设置为粗体文字
        textPaint.setFakeBoldText(true);

        // 上下文字的画笔
        textPaint1 = new Paint(Paint.LINEAR_TEXT_FLAG);
        textPaint1.setAntiAlias(true);
        textPaint1.setColor(upAndDownColor);
        textPaint1.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint1.setTextAlign(Paint.Align.LEFT);

        textPaint1.setTextSize(mTextSize1);

        //步文字的绘制画笔
        stepPaint = new Paint(Paint.LINEAR_TEXT_FLAG);
        stepPaint.setAntiAlias(true);
        stepPaint.setColor(upAndDownColor);
        stepPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        stepPaint.setTextAlign(Paint.Align.LEFT);
        stepPaint.setTextSize(mTextSize1);

        //目标文字的绘制画笔
        downPaint = new Paint(Paint.LINEAR_TEXT_FLAG);
        downPaint.setAntiAlias(true);
        downPaint.setColor(upAndDownColor);
        downPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        downPaint.setTextAlign(Paint.Align.LEFT);
        downPaint.setTextSize(dip2px(getContext(), 11));


        //绘制已完成文字
        downSecondPaint = new Paint(Paint.LINEAR_TEXT_FLAG);
        downSecondPaint.setAntiAlias(true);
        downSecondPaint.setColor(downSecondColor);
        downSecondPaint.setTextSize(dip2px(getContext(), 15));
        // 中间文字内容
        mText = 0;

    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        int halfHeight = getHeight() / 2;
        int halfWidth = getWidth() / 2;
        int center = halfHeight < halfWidth ? halfHeight : halfWidth;
        int radius = center - circleWidth / 2;

        // mColorWheelRectangle是绘制蓝色扇形的画笔
        mColorWheelRectangle.top = halfHeight - radius;
        mColorWheelRectangle.bottom = halfHeight + radius;
        mColorWheelRectangle.left = halfWidth - radius;
        mColorWheelRectangle.right = halfWidth + radius;

        Rect bounds = new Rect();
        String middleText = "";// 中间的文字
        String upText = "";// 上面文字
        String downText = "";// 底部文字

        upText = ResStringUtil.getString(R.string.health_home_step_view_today);
        String downSecondText = ResStringUtil.getString(R.string.health_home_step_view_completed);
        downText = ResStringUtil.getString(R.string.health_home_step_view_target);
        middleText = String.valueOf(mText);
        String step = ResStringUtil.getString(R.string.health_home_step_view_step);

        /**
         * 绘制顶部的文字
         */
        canvas.drawText(
                upText,
                (mColorWheelRectangle.centerX())
                        - (textPaint1.measureText(upText) / 2),
                mColorWheelRectangle.top + bounds.height() / 2
                        + mDistance + circleWidth / 2, textPaint1);

        // 中间文字的画笔
        textPaint.getTextBounds(middleText, 0, middleText.length(), bounds);
        // drawText各个属性的意思(文字,x坐标,y坐标,画笔)
        canvas.drawText(middleText, (mColorWheelRectangle.centerX())
                        - (textPaint.measureText(middleText) / 2),
                mColorWheelRectangle.top + bounds.height() / 2 + 2 * mDistance + circleWidth, textPaint);
        //绘制步的文字
        stepPaint.getTextBounds(step, 0, step.length(), bounds);
        canvas.drawText(step, (mColorWheelRectangle.centerX())
                        - (textPaint.measureText(middleText) / 2) + textPaint.measureText(middleText),
                mColorWheelRectangle.top + bounds.height() / 2 + 2 * mDistance + circleWidth + mTextSize / 2 - mTextSize1, stepPaint);
        //绘制已完成文字
        downSecondPaint.getTextBounds(downSecondText, 0, downSecondText.length(), bounds);
        canvas.drawText(downSecondText, (mColorWheelRectangle.centerX())
                        - (downSecondPaint.measureText(downText) / 2),
                mColorWheelRectangle.centerY() + bounds.height() / 2
                        + mDistance, downSecondPaint);

        downPaint.getTextBounds(downText, 0, downText.length(), bounds);
        canvas.drawText(downText, (mColorWheelRectangle.centerX())
                        - (downPaint.measureText(downText) / 2),
                mColorWheelRectangle.centerY() + bounds.height() / 2
                        + mDistance + dip2px(getContext(), 20), downPaint);


        // 绘制进度圆弧
        drawCircle(canvas, center, radius);
    }

    private void drawCircle(Canvas canvas, int center, int radius) {
        circlePaint.setShader(null); // 清除上一次的shader
        circlePaint.setColor(firstColor); // 设置底部圆环的颜色，这里使用第一种颜色
        circlePaint.setStyle(Paint.Style.STROKE); // 设置绘制的圆为空心
        canvas.drawCircle(center, center, radius, circlePaint); // 画底部的空心圆
        RectF oval = new RectF(center - radius, center - radius, center + radius, center + radius); // 圆的外接正方形

        // 绘制颜色渐变圆环
        // shader类是Android在图形变换中非常重要的一个类。Shader在三维软件中我们称之为着色器，其作用是来给图像着色。
        float shader = 76 / 100;
        LinearGradient linearGradient = new LinearGradient(circleWidth, circleWidth, (getMeasuredWidth()
                - circleWidth) * shader, getMeasuredHeight() - circleWidth, colorArray[0], colorArray[1], Shader.TileMode.MIRROR);
        circlePaint.setShader(linearGradient);
//        circlePaint.setShadowLayer(10, 10, 10, Color.RED);
//        circlePaint.setColor(secondColor); // 设置圆弧的颜色
        circlePaint.setStrokeCap(Paint.Cap.ROUND); // 把每段圆弧改成圆角的

        alphaAngle = currentValue * 360.0f / maxValue * 1.0f; // 计算每次画圆弧时扫过的角度，这里计算要注意分母要转为float类型，否则alphaAngle永远为0
        canvas.drawArc(oval, -90, alphaAngle, false, circlePaint);

    }

    // 测量父布局的大小
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = getDefaultSize(getSuggestedMinimumHeight(),
                heightMeasureSpec);
        int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        int min = Math.min(width, height);
        setMeasuredDimension(min, min);
    }



    public void setUpAndDownColor(int upAndDownColor) {
        this.upAndDownColor = upAndDownColor;
        textPaint1.setColor(upAndDownColor);
        stepPaint.setColor(upAndDownColor);
        downPaint.setColor(upAndDownColor);
        invalidate();
    }


    public void setDownSecondColor(int downSecondColor) {
        this.downSecondColor = downSecondColor;
        downSecondPaint.setColor(downSecondColor);
        invalidate();
    }

    // 中间的数值
    public void setText(int text) {
        mText = text;
        this.postInvalidate();// 可以用子线程更新视图的方法调用。
    }

    /**
     * 设置圆环的宽度
     *
     * @param width
     */
    public void setCircleWidth(int width) {
        this.circleWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources()
                .getDisplayMetrics());
        circlePaint.setStrokeWidth(circleWidth);
        invalidate();
    }

    /**
     * 设置圆环的底色，默认为亮灰色LTGRAY
     *
     * @param color
     */
    public void setFirstColor(int color) {
        this.firstColor = color;
        circlePaint.setColor(firstColor);
        invalidate();
    }

    /**
     * 设置进度条的颜色，默认为蓝色<br>
     *
     * @param color
     */
    public void setSecondColor(int color) {
        this.secondColor = color;
//        circlePaint.setColor(secondColor);
        invalidate();
    }

    /**
     * 设置进度条渐变色颜色数组
     *
     * @param colors 颜色数组，类型为int[]
     */
    public void setColorArray(int[] colors) {
        this.colorArray = colors;
        invalidate();
    }

    /**
     * 按进度显示百分比
     *
     * @param progress 进度，值通常为0到100
     */
    public void setProgress(int progress) {
        int percent = progress * maxValue / 100;
        if (percent < 0) {
            percent = 0;
        }
        if (percent > 100) {
            percent = 100;
        }
        this.currentValue = percent;
        invalidate();
    }

    /**
     * 按进度显示百分比，可选择是否启用数字动画
     *
     * @param progress     进度，值通常为0到100
     * @param useAnimation 是否启用动画，true为启用
     */
    public void setProgress(int progress, boolean useAnimation) {
        int percent = progress * maxValue / 100;
        if (percent < 0) {
            percent = 0;
        }
        if (percent > 100) {
            percent = 100;
        }
        if (useAnimation) // 使用动画
        {
            ValueAnimator animator = ValueAnimator.ofInt(0, percent);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    currentValue = (int) animation.getAnimatedValue();
                    invalidate();
                }
            });
            animator.setInterpolator(new LinearInterpolator());
            animator.setDuration(1000);
            animator.start();
        } else {
            setProgress(progress);
        }
    }



    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

}
